package com.wanyangproject.my;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.activity.DiTuActivity;
import com.wanyangproject.entity.ShangJiaGunaliShiBaiEntity;
import com.wanyangproject.entity.ShangJiaShangJiaGuanLiEntity;
import com.wanyangproject.entity.UserEntity;
import com.wanyangproject.shouye.QiYeXiangQingActivity;
import com.wanyangproject.shouye.YuanQuJieShaoActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ShangJiaGuanLiActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_bianji)
    TextView tvBianji;
    @BindView(R.id.image_shop)
    ImageView imageShop;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shoucang)
    TextView tvShoucang;
    @BindView(R.id.tv_zhengchang_yingye)
    TextView tvZhengchangYingye;
    @BindView(R.id.tv_qisongjia)
    TextView tvQisongjia;
    @BindView(R.id.tv_peisongfei)
    TextView tvPeisongfei;
    @BindView(R.id.tv_yingye_shijian)
    TextView tvYingyeShijian;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.image_ditu)
    ImageView imageDitu;
    @BindView(R.id.tv_dianhua_zixun)
    TextView tvDianhuaZixun;
    @BindView(R.id.tv_peisong_shijian)
    TextView tvPeisongShijian;
    @BindView(R.id.tv_shangjia_fuwu)
    TextView tvShangjiaFuwu;
    @BindView(R.id.image_hongdian_one)
    ImageView imageHongdianOne;
    @BindView(R.id.tv_shangjia)
    TextView tvShangjia;
    @BindView(R.id.image_hongdian_two)
    ImageView imageHongdianTwo;
    @BindView(R.id.tv_ziqu)
    TextView tvZiqu;
//    @BindView(R.id.tv_jieshao)
//    TextView tvJieshao;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.tv_jinri_bidian)
    TextView tvJinriBidian;
    private UserEntity userEntity;
    private String phone;
    private ShangJiaShangJiaGuanLiEntity shangJiaShangJiaGuanLiEntity;
    private WebSettings mWebSettings;
    private String content;
    private static Boolean isOK = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shang_jia_guan_li);
        ButterKnife.bind(this);
        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//        mWebSettings.setTextSize(WebSettings.TextSize.SMALLER);

        //        获取用户信息的网络请求
        initYongHuXinXiHttp();

        //        商家商家管理界面的网络请求
        initShangJiaGuanLiHttp();


        initView();


    }


    @Override
    protected void onResume() {
        super.onResume();
        //        获取用户信息的网络请求
        initYongHuXinXiHttp();

        //        商家商家管理界面的网络请求
        initShangJiaGuanLiHttp();


    }

    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return WebViewUtils.shouldOverrideUrlLoading(view,request,ShangJiaGuanLiActivity.this);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view,url,ShangJiaGuanLiActivity.this);

            }



            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("111111111111111111");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }


            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");

            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);

            }
        });
    }






    //    获取用户信息的网络请求
    private void initYongHuXinXiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Life/user")
                .addHeader("token", ContractUtils.getTOKEN(ShangJiaGuanLiActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "       eeee用户信息");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ShangJiaGuanLiActivity.this,response);
                        System.out.println(response + "    获取个人用户信息的网络请求");

                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            userEntity = gson.fromJson(response, UserEntity.class);
                            phone = userEntity.getResponse().getUsername();//获取手机号
                            System.out.println(phone + "     用户的手机号");

                        }
                    }
                });
    }


//    @Override
//    protected void onResume() {
//        super.onResume();
//        //        商家商家管理界面的网络请求
//        initShangJiaGuanLiHttp();
//    }

    //    商家商家管理界面的网络请求
    private void initShangJiaGuanLiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "Shop/shopfind")
                .addHeader("token", ContractUtils.getTOKEN(ShangJiaGuanLiActivity.this))
                .addParams("parkId", ContractUtils.getParkId(ShangJiaGuanLiActivity.this))
                .addParams("phone", ContractUtils.getPhone(ShangJiaGuanLiActivity.this))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ShangJiaGuanLiActivity.this,response);
                        System.out.println(response + "        商家商家管理界面的网络请求");
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            shangJiaShangJiaGuanLiEntity = gson.fromJson(response, ShangJiaShangJiaGuanLiEntity.class);

                            if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getCost().equals("")){
                                shangJiaShangJiaGuanLiEntity.getResponse().getShop().setCost("0");
                            }


                            if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getPhoto() != null){
                                if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getPhoto().equals("park.hostop.net/")) {
                                    Glide.with(ShangJiaGuanLiActivity.this).load(R.drawable.shangdian).into(imageShop);
                                } else {  //头像
                                    Glide.with(ShangJiaGuanLiActivity.this).load(ContractUtils.PHOTO_URL + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getPhoto()).into(imageShop);
                                }
                            }



                            if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getCollection() == null){

                            }else{
                                tvShoucang.setText(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getCollection()+"收藏");
                            }




                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getNickname() == null) {

                            } else { // 商家名称
                                tvShopName.setText(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getNickname());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStarting() == null) {

                            } else { //起送价
                                tvQisongjia.setText("起送价¥" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStarting());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getCost() == null) {

                            } else { // 配送费
                                tvPeisongfei.setText("配送费¥" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getCost());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() == null && shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time() == null) {

                            } else {  //  营业时间
                                tvYingyeShijian.setText("营业时间：" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() + " ~ " + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() == null && shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time() == null) {

                            } else {  //  营业时间
                                tvTime.setText("营业时间：" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() + " ~ " + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBaidu_address() == null) {

                            } else { // 商家位置
                                tvAddress.setText(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBaidu_address());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getPhone() == null) {

                            } else { // 电话咨询
                                tvDianhuaZixun.setText("电话咨询：" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getPhone());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() == null && shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time() == null) {

                            } else {  //  配送时间
                                tvPeisongShijian.setText("配送时间：" + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getStar_time() + " ~ " + shangJiaShangJiaGuanLiEntity.getResponse().getShop().getEnd_time());
                            }


                            if (shangJiaShangJiaGuanLiEntity.getResponse().getShop().getContent() == null) {

                            } else { // 商家介绍
                                //                            内容
                                content = shangJiaShangJiaGuanLiEntity.getResponse().getShop().getContent();
                                String newContent = getNewContent(content);
                                if(!newContent.endsWith("</p>")){
                                    newContent = newContent + "</p>";
                                }
                                webView.loadDataWithBaseURL("http://www.baidu.com", "<style>* {font-size:14px;line-height:20px;}p {color:#000000;}</style>"+newContent, "text/html", "UTF-8", null);
//                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content), "text/html", "UTF-8", null);
                            }


//                            //    2：商家配送1：到店自取3：都支持
                            if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getService().equals("2")){
                                imageHongdianOne.setVisibility(View.VISIBLE);
                                tvShangjia.setVisibility(View.VISIBLE);
                                imageHongdianTwo.setVisibility(View.GONE);
                                tvZiqu.setVisibility(View.GONE);
                            }else if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getService().equals("1")){
                                imageHongdianOne.setVisibility(View.GONE);
                                tvShangjia.setVisibility(View.GONE);
                                imageHongdianTwo.setVisibility(View.VISIBLE);
                                tvZiqu.setVisibility(View.VISIBLE);
                            }else if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getService().equals("3")){
                                imageHongdianOne.setVisibility(View.VISIBLE);
                                tvShangjia.setVisibility(View.VISIBLE);
                                imageHongdianTwo.setVisibility(View.VISIBLE);
                                tvZiqu.setVisibility(View.VISIBLE);
                            }



                            if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness() != null){
                                if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness().equals("1")){
                                    tvJinriBidian.setVisibility(View.GONE);
                                    tvZhengchangYingye.setVisibility(View.VISIBLE);

                                }else if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness().equals("2")){
                                    tvZhengchangYingye.setVisibility(View.GONE);
                                    tvJinriBidian.setVisibility(View.VISIBLE);
                                }
                            }
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            ShangJiaGunaliShiBaiEntity shangJiaGunaliShiBaiEntity = gson.fromJson(response, ShangJiaGunaliShiBaiEntity.class);
                            Toast.makeText(ShangJiaGuanLiActivity.this, shangJiaGunaliShiBaiEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {
//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }


    @OnClick({R.id.image_back, R.id.tv_bianji, R.id.image_shop, R.id.tv_shop_name, R.id.tv_shoucang, R.id.tv_jinri_bidian,R.id.tv_zhengchang_yingye, R.id.tv_qisongjia, R.id.tv_peisongfei, R.id.tv_yingye_shijian, R.id.tv_time, R.id.tv_address, R.id.image_ditu, R.id.tv_dianhua_zixun, R.id.tv_peisong_shijian, R.id.tv_shangjia_fuwu, R.id.image_hongdian_one, R.id.tv_shangjia, R.id.image_hongdian_two, R.id.tv_ziqu, R.id.tv_jianjie})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
//            编辑
            case R.id.tv_bianji:
                Intent intent = new Intent(ShangJiaGuanLiActivity.this, ShangJiaBianJiActivity.class);
                startActivity(intent);
                break;
            case R.id.image_shop:
                break;
            case R.id.tv_shop_name:
                break;
            case R.id.tv_shoucang:
                break;
//            正常营业
            case R.id.tv_zhengchang_yingye:
                if(shangJiaShangJiaGuanLiEntity == null){
                    return;
                }
                if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness() == null){

                }else{
                    String business = shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness();
                    business = "2";
                    tvZhengchangYingye.setVisibility(View.GONE);
                    tvJinriBidian.setVisibility(View.VISIBLE);
//                切换商家营业状态的网络请求
                    initQieHuanYingYeZhuangTaiHttp(business);
                }

                break;
//            今日闭店
            case R.id.tv_jinri_bidian:
                if(shangJiaShangJiaGuanLiEntity == null){
                    return;
                }
                if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness() == null){

                }else{
                    String business1 = shangJiaShangJiaGuanLiEntity.getResponse().getShop().getBusiness();
                    business1 = "1";
                    tvJinriBidian.setVisibility(View.GONE);
                    tvZhengchangYingye.setVisibility(View.VISIBLE);
                    //                切换商家营业状态的网络请求
                    initQieHuanYingYeZhuangTaiHttp(business1);
                }

                break;
            case R.id.tv_qisongjia:
                break;
            case R.id.tv_peisongfei:
                break;
            case R.id.tv_yingye_shijian:
                break;
            case R.id.tv_time:
                break;
            case R.id.tv_address:
                break;
//            地图
            case R.id.image_ditu:
                if(shangJiaShangJiaGuanLiEntity == null){
                    Toast.makeText(this, "暂无地址！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(shangJiaShangJiaGuanLiEntity.getResponse().getShop().getLat().equals("") && shangJiaShangJiaGuanLiEntity.getResponse().getShop().getLng().equals("")){
                    Toast.makeText(this, "暂无地址！", Toast.LENGTH_SHORT).show();
                    return;
                }

                Intent intent1 = new Intent(ShangJiaGuanLiActivity.this, DiTuActivity.class);
                intent1.putExtra("lat",shangJiaShangJiaGuanLiEntity.getResponse().getShop().getLat());
                intent1.putExtra("lng",shangJiaShangJiaGuanLiEntity.getResponse().getShop().getLng());
                intent1.putExtra("name",shangJiaShangJiaGuanLiEntity.getResponse().getShop().getNickname());
                startActivity(intent1);

                break;
            case R.id.tv_dianhua_zixun:
                break;
            case R.id.tv_peisong_shijian:
                break;
            case R.id.tv_shangjia_fuwu:
                break;
            case R.id.image_hongdian_one:
                break;
            case R.id.tv_shangjia:
                break;
            case R.id.image_hongdian_two:
                break;
            case R.id.tv_ziqu:
                break;
            case R.id.tv_jianjie:
                break;
        }
    }

//    切换商家营业状态的网络请求
    private void initQieHuanYingYeZhuangTaiHttp(String zhuangtai) {

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL+"Shop/business")
                .addHeader("token",ContractUtils.getTOKEN(ShangJiaGuanLiActivity.this))
                .addParams("parkId",ContractUtils.getParkId(ShangJiaGuanLiActivity.this))
                .addParams("phone",phone)
                .addParams("type",zhuangtai)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ContractUtils.Code500(ShangJiaGuanLiActivity.this,response);
                        System.out.println(response+"     切换商家营业状态的网络请求");

                    }
                });
    }
}
